package com.dimples.dd.gateway.filter.logging;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 网关的访问日志过滤器
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/5/24
 */
@Component
@Slf4j
public class AccessLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //日志打印
        printLog(exchange);

        return chain.filter(exchange);
    }


    private void printLog(ServerWebExchange exchange) {
        URI originUri = exchange.getRequest().getURI();
        URI targetUrl = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);

        if (targetUrl != null && route != null) {
            log.info("转发请求: {}://{}{} --> 目标服务：{}, 目标地址：{}://{}{}, 转发时间: {}"
                    , originUri.getScheme(), originUri.getAuthority(), originUri.getPath(), route.getId()
                    , targetUrl.getScheme(), targetUrl.getAuthority(), targetUrl.getPath()
                    , DateUtil.now());
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
